import type { RouteRecordRaw } from 'vue-router'
import type { MenuOption } from 'naive-ui'
import { RouterLink } from 'vue-router'
import { getMenuInfo } from '@/api/base/Base'
import { AppstoreFilled as AppstoreFilledIcon } from '@vicons/antd'
import { Menu as MenuIcon } from '@vicons/carbon'
import router from '@/router'

export const useMenuStore = defineStore('menu', {
  state() {
    return {
      menuInfo: [] as MenuInfo[]
    }
  },
  getters: {
    menuRoutes(): RouteRecordRaw[] {
      return this.menuInfo.map((ele) => {
        const children: RouteRecordRaw[] = ele.menus?.map((subEle) => {
          return {
            name: subEle.name,
            path: `${subEle.code}`,
            component: () => import(`../../views/${ele.code}/${subEle.code}/Index.vue`)
          }
        })
        return {
          name: ele.name,
          path: `/${ele.code}`,
          component: () => import(`@/views/layout/Index.vue`),
          children
        }
      })
    },
    menuOptions(): MenuOption[] {
      return this.menuInfo.map((ele) => {
        const children = ele.menus?.map((subEle) => {
          return {
            key: `/${ele.code}/${subEle.code}`,
            label: () => {
              return h(
                RouterLink,
                {
                  to: { path: `/${ele.code}/${subEle.code}` }
                },
                { default: () => subEle.name }
              )
            },
            icon: renderIcon(MenuIcon)
          }
        })
        return {
          key: `/${ele.code}`,
          label: ele.name,
          icon: renderIcon(AppstoreFilledIcon),
          children
        }
      })
    }
  },
  actions: {
    async InitMenuInfo() {
      const { data } = await getMenuInfo(getRoleId())
      this.menuInfo = data
      this.InitMenuRoute()
    },
    InitMenuRoute() {
      this.menuRoutes.forEach((ele) => {
        router.addRoute(ele)
      })
    }
  }
})
